package com.ls.queue;

public class CircleArrayQueue {
    public static void main(String[] args) {
        CircleArrayQueue queue = new CircleArrayQueue(3);//实际只有2个空间
        queue.addQueue(10);
        queue.addQueue(20);
        queue.addQueue(20);

        queue.showQueue();

        System.out.println(queue.headQueue());
        System.out.println(queue.getQueue());
        System.out.println(queue.getQueue());

    }


    private int maxSize;
    private int front;//头
    private int rear;//尾
    private int[] arr;

    public CircleArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
        front = 0;
        rear = 0;//初始值0
    }

    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    public boolean isEmpty() {
        return rear == front;
    }

    public void addQueue(int n) {
        if (isFull()) {
            System.out.println("isFull");
            return;
        }
        arr[rear] = n;
        rear = (rear + 1) % maxSize;
    }

    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("isEmpty");
        }
        int temp = 0;
        temp = front;
        front = (front + 1) % maxSize;
        return arr[temp];
    }

    public void showQueue() {
        if (isEmpty()) {
            System.out.println("isEmpty");
        }
        for (int i = front; i < front + size(); i++) {

            System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
        }
    }

    public int size() {
        int i = (rear + maxSize - front) % maxSize;
        return i;
    }


    public int headQueue() {
        if (isEmpty()) {
            throw new RuntimeException("isEmpty");
        }
        return arr[front];
    }

}

